package cc.ufinity.networkdiagnose.widget;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class WebauthTestWidgetProxy extends GeneralTestWidget {

    private Activity ctx;
    private final Handler handler;
    private WebAuthManager webAuthManager;
    private WlanManager wlanManager;
    private Button btnback;
    private Button btnRetest;
    private int frequency;
    private int current;
    private String defaultUrl;
    private LinearLayout webAuthLayout;
    private LinearLayout webauthTestChartLayout;
    private ScrollView sv;
    private boolean processing;
    private long loginTotalTime;
    private int lsuccessTimes;
    private int osuccessTimes;
    private double xdata[];
    private double lydata[];
    private double oydata[];
    private long logoutTotalTime;
    private static String TAG = "WebauthTestWidget";

    private EditText userNameEt;
    private EditText pwdEt;
    private Button btnStart;
    private int testedTimes;

    private Task task;

    public WebauthTestWidgetProxy(Activity context) {
        super(context);
        this.ctx = context;
        inflate(context, R.layout.webauth_test_widget_proxy, this);
        btnback = (Button) this.findViewById(R.id.webauth_test_proxy_btnback);
        defaultUrl = ctx.getResources().getString(R.string.default_url);
        sv = (ScrollView) this.findViewById(R.id.webauth_test_proxy_ScrView);
        webAuthLayout = (LinearLayout) this.findViewById(R.id.webauth_test_proxy_layout);
        webauthTestChartLayout = (LinearLayout) this.findViewById(R.id.webauthTestChartLayoutProxy);
        userNameEt = (EditText) this.findViewById(R.id.userNameEditTextProxy);
        pwdEt = (EditText) this.findViewById(R.id.pwdEditTextProxy);
        btnStart = (Button) this.findViewById(R.id.btn_webauth_proxy_start);
        btnback.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                backToTask(ctx);
            }
        });


        btnStart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                start();
            }
        });

        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.DO_NEXT_TEST:
                    showNextText();
                    break;
                default:
                    update(msg.what);
                }
            }
        };
        webAuthManager = new WebAuthManager(ctx);
        webAuthManager.setHandler(handler);
        wlanManager = new WlanManager(ctx);
        wlanManager.setHandler(handler);
        task = (Task)ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        frequency = task.testCount;
        //scanWifi();
    }
/*
    private void scanWifi() {
        this.showMessageDialog(ctx, "正在扫描附近Wifi热点...");
        new Thread() {
            public void run() {
                wlanManager.startScan();
            }
        }.start();
    }

    private void enableNetWork(final ScanResult scan) {
        this.showMessageDialog(ctx, "正在连接Wifi...");
        new Thread() {
            public void run() {
                wlanManager.connect(scan);
            }
        }.start();

    }*/
    
    private void showNextText() {
        if(task.taskType.equals(Task.TASK_TYPE_Y)){
            SegregateTestWidgetProxy stw = new SegregateTestWidgetProxy(ctx);
            ctx.setContentView(stw);
        }else{
            TaskResult tr = new TaskResult(ctx);
            ctx.setContentView(tr);
        }
        
    }

    private void doNextTest() {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                sendMsg(MessageWhat.DO_NEXT_TEST, handler);
            }
        };
        Timer t = new Timer();
        t.schedule(timerTask, TASK_PERFORM_INTERVAL);
        this.showMessage(ctx, "WEB认证测试已完成，10秒后进入下一环节.");
    }
    private void update(int what) {
        testedTimes++;
        this.setDialogProgress(testedTimes);
        StringBuffer s = new StringBuffer();
        xdata[current - 1] = current;
        long costTime = (webAuthManager.getEndTime() - webAuthManager.getStartTime()) / 1000;
        if (MessageWhat.LOGIN_SUCCESS == what) {
            s.append("第").append(current).append("次 登录成功，时延：").append(costTime).append('s');
            loginTotalTime += costTime;
            lydata[current - 1] = costTime;
            lsuccessTimes++;
            TextView tv = new TextView(ctx);
            tv.setTextSize(12);
            tv.setText(s);
            webAuthLayout.addView(tv);
        } else if (MessageWhat.LOGOUT_SUCCESS == what) {
            s.append("第").append(current).append("次 下线成功，时延：").append(costTime).append('s');
            logoutTotalTime += costTime;
            oydata[current - 1] = costTime;
            osuccessTimes++;
            TextView tv = new TextView(ctx);
            tv.setTextSize(12);
            tv.setText(s);
            webAuthLayout.addView(tv);
        } else if (what == MessageWhat.LOGIN_FAILED) {
            s.append("第").append(current).append("次 登录失败");
            lydata[current - 1] = 0;
            TextView tv = new TextView(ctx);
            tv.setTextSize(12);
            tv.setText(s);
            webAuthLayout.addView(tv);
        } else if (what == MessageWhat.LOGOUT_FAILED) {
            s.append("第").append(current).append("次 下线失败");
            oydata[current - 1] = 0;
            TextView tv = new TextView(ctx);
            tv.setTextSize(12);
            tv.setText(s);
            webAuthLayout.addView(tv);

        }
        if (MessageWhat.DONE == what) {
            long lavg = (lsuccessTimes == 0) ? 0 : loginTotalTime / lsuccessTimes;
            // long oavg = (osuccessTimes == 0) ? 0 : logoutTotalTime /
            // osuccessTimes;
            float sucessRate = ((float) lsuccessTimes / frequency) * 100;
            float offSuccessRate = ((float) osuccessTimes / frequency) * 100;
            s = new StringBuffer();
            s.append("认证次数：").append(frequency).append("次; ");
            s.append("成功次数：").append(lsuccessTimes).append('次').append('\n');
            s.append("认证平均时延：").append(lavg).append('s').append('\n');
            s.append("认证成功率：").append(sucessRate).append('%').append(" 下线成功率：").append(offSuccessRate).append('%');
            TextView tv = new TextView(ctx);
            tv.setTextSize(13);
            tv.setTextColor(Color.CYAN);
            tv.setText(s);
            webAuthLayout.addView(tv);
            drawChart();

            task.endTime = StringUtils.getDateTime();
            task.webDelay = String.valueOf(lavg);
            task.webSuccessRate = String.valueOf(sucessRate);
            task.webOffSuccessRate = String.valueOf(offSuccessRate);
            
            ctx.getIntent().putExtra(TAG_REFER_TASK, task);

            dismissProgressDialog();
            doNextTest();
        }
        this.setScrollViewDown(sv);
        processing = false;
    }

    private void drawChart() {
        webauthTestChartLayout.removeAllViews();
        ChartManager cm = new ChartManager(ctx, 10, 30);
        String chartTitle = "WEB登录认证/下线测试";
        String[] lineTitles = new String[] { "WEB登录认证测试", "WEB下线测试" };
        List<double[]> x = new ArrayList<double[]>(2);
        List<double[]> y = new ArrayList<double[]>(2);
        x.add(xdata);
        y.add(lydata);
        x.add(xdata);
        y.add(oydata);
        int[] colors = new int[] { Color.BLUE, Color.GREEN };
        View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x, y);
        webauthTestChartLayout.addView(lineChart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    }

    private void clear() {
        testedTimes = 0;
        current = 0;
        loginTotalTime = 0;
        logoutTotalTime = 0;
        lsuccessTimes = 0;
        osuccessTimes = 0;
        xdata = null;
        lydata = null;
        oydata = null;
        processing = false;
        webAuthLayout.removeAllViews();
    }

    public void start() {
        final String userName = userNameEt.getText().toString();
        final String pwd = pwdEt.getText().toString();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(pwd)) {
            this.showMessage(ctx, "请输入账号或密码.");
            return;
        }
        clear();
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp != null) {
            this.showProgressDialog(ctx, "正在进行WEB认证测试...", frequency * 2);
            xdata = new double[frequency];
            lydata = new double[frequency];
            oydata = new double[frequency];
            new Thread() {
                public void run() {
                    while (current < frequency && executable) {
                        if (!processing) {
                            processing = true;
                            webAuthManager.setStartTime(System.currentTimeMillis());
                            current++;
                            boolean success = webAuthManager.auth(defaultUrl, userName, pwd);
                            webAuthManager.setEndTime(System.currentTimeMillis());
                            if (success)
                                webAuthManager.sendMsg(MessageWhat.LOGIN_SUCCESS);
                            else {
                                webAuthManager.sendMsg(MessageWhat.LOGIN_FAILED);
                            }

                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                Log.e(TAG, "WEB登录认证时线程等待出错：", e);
                            }
                            webAuthManager.setStartTime(System.currentTimeMillis());
                            if (success) {
                                success = webAuthManager.logout();
                            }
                            webAuthManager.setEndTime(System.currentTimeMillis());
                            if (success)
                                webAuthManager.sendMsg(MessageWhat.LOGOUT_SUCCESS);
                            else {
                                webAuthManager.sendMsg(MessageWhat.LOGOUT_FAILED);
                            }

                            if (current == frequency) {
                                webAuthManager.sendMsg(MessageWhat.DONE);
                            }
                        }
                    }
                }
            }.start();
        }
    }
}
